<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Upload extends Admin_Controller {

	public $model = "upload";
	public $view = "upload";
    var $theme_data = array(
        'layout_main' => 'layout',
        'left' => 'include/leftcp',
    );

	public $permissionPost = 'Permissions.Upload.Post';
	
    function __construct() {
        parent::__construct();
		$this->resCode = 'System.Upload';
		
		$this->output->set_header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		$this->output->set_header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
		$this->output->set_header("Cache-Control: post-check=0, pre-check=0", false);
		$this->output->set_header("Pragma: no-cache");
		@set_time_limit(5 * 60);
		
		$this->init();
    }
	
	function init() {
		$targetDir = $this->folder_upload . DIRECTORY_SEPARATOR . date('Ymd');
		if (!file_exists($targetDir)) {
			@mkdir($targetDir);
		}
		$config =  array(
		  'upload_path'     => $targetDir,
		  'upload_url'      => base_url()."dataupload/",
		  'allowed_types'   => "gif|jpg|png|jpeg|pdf|doc|xml",
		  'overwrite'       => TRUE,
		  'max_size'        => "1000KB",
		  'max_height'      => "768",
		  'max_width'       => "1024"  
		);
		$this->load->library('upload');
		$this->upload->initialize($config);
	}
	
	function index($page = 0){
		echo 'Upload to here.';
		die();
	}
	
	function do_upload() {
		$targetDir = $this->folder_upload . DIRECTORY_SEPARATOR . date('Ymd');
		if (!file_exists($targetDir)) {
			@mkdir($targetDir);
		}
		$cleanupTargetDir = true; // Remove old files
		$maxFileAge = 5 * 3600; // Temp file age in seconds
		
		// Get a file name
		if (isset($_REQUEST["name"])) {
			$fileName = $_REQUEST["name"];
		} elseif (!empty($_FILES)) {
			$fileName = $_FILES["file"]["name"];
		} else {
			$fileName = uniqid("file_");
		}

		$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
		// Check if file has been uploaded
		$result = array();
		if($this->upload->do_multi_upload("file")) {
            //Print data for all uploaded files.
            $result = $this->upload->get_multi_upload_data();
        }
		die(json_encode($result));
	}
}
